package com.qigao.erp.web.except;

import com.alibaba.fastjson.JSONObject;
import com.qigao.erp.commons.enums.Result;
import com.qigao.erp.commons.enums.ResultCode;
import com.qigao.erp.commons.exceptions.BusinessException;
import org.apache.shiro.ShiroException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author luiz
 * @Title: SsoShiroHandler
 * @ProjectName user-client
 * @Description: TODO
 * @date 2019-01-02 13:29
 */
public class SsoShiroExceptionHandler implements HandlerExceptionResolver {
    private static Logger logger = LoggerFactory.getLogger(SsoShiroExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception e) {
        Result<String> userResult = Result.newError(ResultCode.FAIL);
        ModelAndView mv = new ModelAndView();
        logger.error("权限异常:{}", e);
        if (e instanceof ShiroException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            userResult.setErrorCode(ResultCode.FOR_UNAUTHORIZED);
        }if (e instanceof BusinessException) {
            userResult.setError(((BusinessException) e).getCode(),((BusinessException) e).getMsg());
        }
        try {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSONObject.toJSONString(userResult));
        } catch (IOException e1) {
            logger.error(e1.getMessage(), e1);
        }
        return mv;
    }
}
